/*
 * EcommUtil.java
 *
 * Created on 2006年10月26日, 下午2:18
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.ecomm.util;


import java.io.*;
import java.util.*;

public class StringUtils {
    /** 说明: 将字符串变量由null转换为""串
     *  @param  需要处理的字符串
     *  @return 处理后的字符串
     */
    public static String  nullToStr(String str) {
        if (str==null) str="";
        return str.trim();
    }
    private static String strForRandom = "abcdefghijklmnopqrstuvwxyz";
    
    /**
     * This method reads a properties file which is passed as
     * the parameter to it and load it into a java Properties
     * object and returns it.
     * @param <b>file</b> Represents the .properties file
     * @return <b>Properties</b>The properties object
     * @throws <b>IOException</b> The exception this method can throw
     */
    public static Properties loadParams( String file )
    throws IOException {
        
        // Loads a ResourceBundle and creates Properties from it
        Properties prop = new Properties();
        ResourceBundle bundle = ResourceBundle.getBundle( file );
        
        Enumeration enuma = bundle.getKeys();
        String key = null;
        
        while( enuma.hasMoreElements() ) {
            key = (String)enuma.nextElement();
            prop.put( key, bundle.getObject( key ) );
        }
        return prop;
    }
    
    /**
     * This method is generate the radom password.
     * @return <b>String</b>The random string.
     * @throws
     */
    
    
    /**
     * <pre>
     * For example:
     * String strVal="This is a dog";
     * String strResult=CTools.replace(strVal,"dog","cat");
     * The result: "This is cat"
     *
     * @param strSrc: the string for replacing.
     * @param strOld: the old string.
     * @param strNew: the new string.
     * @return the replaced string and the untouched string.
     * <pre>
     */
    
    public static final String replace(String strSrc,String strOld,String strNew) {
        if(strSrc==null||strOld==null||strNew==null)
            return "";
        
        int i=0;
        
        if((i=strSrc.indexOf(strOld,i))>=0) {
            char[] arr_cSrc=strSrc.toCharArray();
            char[] arr_cNew=strNew.toCharArray();
            
            int intOldLen=strOld.length();
            StringBuffer buf=new StringBuffer(arr_cSrc.length);
            buf.append(arr_cSrc,0,i).append(arr_cNew);
            
            i+=intOldLen;
            int j=i;
            
            while((i=strSrc.indexOf(strOld,i))>0) {
                buf.append(arr_cSrc,j,i-j).append(arr_cNew);
                i+=intOldLen;
                j=i;
            }
            
            buf.append(arr_cSrc,j,arr_cSrc.length-j);
            
            return buf.toString();
        }
        
        return strSrc;
    }
    
    
    /**
     * 在将数据存入数据库前转换
     *
     * @param strVal 要转换的字符串
     * @return 从“ISO8859_1”到“GBK”得到的字符串
     */
    public static final String toChinese(String strVal) {
        try {
            if(strVal==null) {
                return "";
            } else {
                strVal=strVal.trim();
                strVal=new String(strVal.getBytes("ISO8859_1"), "GBK");
                strVal=replace(strVal,"'","''");
                return strVal;
            }
        } catch(Exception exp) {
            return "";
        }
    }   
    /**
     * 在将数据存入数据库前转换
     *传入编码方式，返回想要的指定编码
     * @param strVal 要转换的字符串
     * @return 从“ISO8859_1”到“GBK”得到的字符串
     */
    public static final String deCode(String strVal,String byteOld,String byteNew) {
        try {
            if(strVal==null) {
                return "";
            } else {
                strVal=strVal.trim();
                strVal=new String(strVal.getBytes(byteOld), byteNew);
                return strVal;
            }
        } catch(Exception exp) {
            return "";
        }
    }
    /**
     * 在将数据存入数据库前转换,不进行Replace的转换
     *
     * @param strVal 要转换的字符串
     * @return 从"ISO8859_1"到"GBK"得到的字符串
     */
    
    public static final String toChineseNoReplace(String strVal) {
        try {
            if(strVal==null) {
                return "";
            } else {
                strVal=strVal.trim();
                strVal=new String(strVal.getBytes("ISO8859_1"), "GBK");
                return strVal;
            }
        } catch(Exception exp) {
            return "";
        }
    }
    
    /**
     * 将数据从数据库中取出后转换
     *
     * @param strVal 要转换的字符串
     * @return 从“GBK”到“ISO8859_1”得到的字符串
     */
    public static final String toISO(String strVal) {
        try {
            if(strVal==null) {
                return "";
            } else {
                strVal=new String(strVal.getBytes("GBK"), "ISO8859_1");
                return strVal;
            }
        } catch(Exception exp) {
            return "";
        }
    }
    
    /**
     * 真实的转吗
     * @param strIn
     * @return
     */
    
    public static String IsoToGBK_real(String strIn) {
        String strOut = null;
        if(strIn == null) return "";
        try {
            byte[] b = strIn.getBytes("ISO8859_1");
            strOut = new String(b,"GBK");
        } catch(UnsupportedEncodingException e) {
        }
        
        return strOut;
    }
    
    /**
     * 把GBK转变ISO8859_1
     * @param strIn String
     * @return String
     */
    public static String GBKToIso_real(String strIn) {
        String strOut = null;
        if(strIn == null) return "";
        try {
            byte[] b = strIn.getBytes("GBK");
            strOut = new String(b,"ISO8859_1");
        } catch(UnsupportedEncodingException e) {
        }
        
        return strOut;
    }
    
    /**
     * Replaces all instances of oldString with newString in line with the
     * added feature that matches of newString in oldString ignore case.
     *
     * @param line the String to search to perform replacements on
     * @param oldString the String that should be replaced by newString
     * @param newString the String that will replace all instances of oldString
     *
     * @return a String will all instances of oldString replaced by newString
     */
    public static final String replaceIgnoreCase(String line, String oldString,
            String newString) {
        if (line == null) {
            return null;
        }
        String lcLine = line.toLowerCase();
        String lcOldString = oldString.toLowerCase();
        int i=0;
        if ((i=lcLine.indexOf(lcOldString, i)) >= 0) {
            char [] line2 = line.toCharArray();
            char [] newString2 = newString.toCharArray();
            int oLength = oldString.length();
            StringBuffer buf = new StringBuffer(line2.length);
            buf.append(line2, 0, i).append(newString2);
            i += oLength;
            int j = i;
            while ((i=lcLine.indexOf(lcOldString, i)) > 0) {
                buf.append(line2, j, i-j).append(newString2);
                i += oLength;
                j = i;
            }
            buf.append(line2, j, line2.length - j);
            return buf.toString();
        }
        return line;
    }
    
    public static String[] separate(String line, String separator) {
        StringTokenizer tokenizer = new StringTokenizer(line, separator);
        String[] result = new String[tokenizer.countTokens()];
        int count = 0;
        while (tokenizer.hasMoreTokens()) {
            result[count++] = tokenizer.nextToken();
        }
        
        return result;
    }
    
    /**
     * 说明：对字符串进行分割
     * @param strSuper 源字符串
     * @param strSing  分割字符串
     * @return Vector
     */
    public  static String[] split(String line,String newString) {
        int begin = 0;
        int end = 0;
        ArrayList strList = new ArrayList();
        if (line == null) {
            return null;
        }
        if ( newString == "" ) {
            int i;
            for ( i=0; i<line.length(); i++ ) {
                strList.add( line.substring(i,i+1) );
            }
            return (String[]) strList.toArray(new String[strList.size()]);
        }
        
        end = line.indexOf(newString);
        if ( end == -1 ) {
            strList.add(line);
            return (String[]) strList.toArray(new String[strList.size()]);
        } else {
            while ( end >= 0 ) {
                strList.add(line.substring(begin,end));
                begin = end + newString.length();
                end = line.indexOf(newString,begin);
            }
            strList.add(line.substring(begin,line.length()));
            return (String[]) strList.toArray(new String[strList.size()]);
        }
    }
    
    /**
     * 得到有排序功能的表头字段的HTML代码 add by 陈刚
     * 参数说明(当前排序字段 cur_sort_field,当前排序类型 cur_sort_type,表头字段名 title,表字段对应的数据库字段名 sort_field,当前FORM名 form_name,Script程序的入口变量 checkForm_var,升序图标路径 asc_pic,降序图标路径 desc_pic)
     * 返回值例:<a href=javaScript:form1.sort_field.value='type';form1.sort_type.value='desc';checkForm('turnPage')>上报类别</a><img src=../images/up.gif >
     * 使用实例:StringUtils.getTableTitleHtml(sort_field,sort_type,"上报时间","write_time","form1","turnPage","../images/asc.gif","../images/desc.gif")
     * 使用条件:
     * (1)生成的代码必须在<FORM>...</FORM>中
     * (2)在<FORM>中增加类似如下的语句,用以保存排序的两变量值
     *		<input name="sort_field" type="hidden">
     *          <input name="sort_type" type="hidden">
     * (3)页面必须有如类似如下的JavaScript函数以便于对点击标头键接的响应
     *   <script language="javascript">
     *	  function checkForm(operType){
     *		var errMsg="";
     *		if(operType=='turnPage'){
     *		form1.action="sendlist.jsp?isBack=1";
     *		form1.submit();
     *		return true;
     *	  }
     *   </script>
     */
    public static String getTableTitleHtml(String cur_sort_field, String cur_sort_type, String title, String sort_field, String form_name, String checkForm_var, String asc_pic, String desc_pic) {
        String imgStr = "";
        if (cur_sort_field.trim().equals(sort_field.trim())) {
            //当本字段为当前的排序字段时显示排序的小图片
            if (cur_sort_type.trim().equals("asc")) {
                imgStr = "<img src=" + asc_pic.trim() + ">";
            } else {
                imgStr = "<img src=" + desc_pic.trim() + ">";
            }
            //如果本字段为当前的排序字段,则与原来的排序相反;否则为升序
            if (cur_sort_type.trim().equals("asc")) {
                cur_sort_type = "desc";
            } else {
                cur_sort_type = "asc";
            }
        } else {
            //默认为升序
            cur_sort_type = "asc";
        }
        String titleHtml = "<a href=javaScript:" + form_name.trim() + ".sort_field.value='" + sort_field.trim() + "';" + form_name.trim() + ".sort_type.value='" + cur_sort_type.trim() + "';checkForm('" + checkForm_var.trim() + "')>" + title.trim() + "</a>" + imgStr;
        return titleHtml;
    }
    /**
     * System.out.println(substring(10,"一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十"));
     *    输出：一二三四五六七八九十...
     *你想要输入字符的是多少个之后的，默认是15个字
     * length 字符长度
     * name 字符的名字
     */
    public static String substring(int length,String name){
        if(name == null || name.equals("")){
            return "";
        }else if(name.length() <= length){
            return name;
        }else if(name.length() > length){
            return name.substring(0,length)+"...";
        }else{
            return name.substring(0,15);
        }
    }
    public static String getPageTitleHtml(String title) {
        String result = "";
        result = "<table width='99%' height='30' border='0' cellpadding='0' cellspacing='3'>";
        result += "<tr><td><strong>" + title + "</strong></td></tr>";
        result += "<tr><td><hr size='1' noshade></td></tr></table>";
        return result;
    }
    
    
    /**
     * 将字符串变量由null转换为""串 add by 陈刚
     * @param  需要处理的字符串
     * @return 处理后的字符串
     */
    public static String noNullStr(String str) {
        if (str == null || str.equalsIgnoreCase("null")) {
            return "";
        }
        return str;
    }
    
    
    
    
    /**
     * 页面段落文字处理
     */
    public static String DbToHtmlText(String str){
        StringUtils suil = new StringUtils();
        str=suil.replace( str,"\n","<br>" );
        str=suil.replace( str,"\r","<br>" );
        str=suil.replace( str,"  ","　" );
        return str;
    }
    //*********************************************************************
    //* Base64 - a simple base64 encoder and decoder.
    //*
    //*     Copyright (c) 1999, Bob Withers - bwit@pobox.com
    //*
    //* This code may be freely used for any purpose, either personal
    //* or commercial, provided the authors copyright notice remains
    //* intact.
    //*********************************************************************
    
    /**
     * Encodes a String as a base64 String.
     *
     * @param data a String to encode.
     * @return a base64 encoded String.
     */
    public static String encodeBase64(String data) {
        return encodeBase64(data.getBytes());
        // return data;
    }
    
    
    /**
     * Encodes a byte array into a base64 String.
     *
     * @param data a byte array to encode.
     * @return a base64 encode String.
     */
    public static String encodeBase64(byte[] data) {
        int c;
        int len = data.length;
        StringBuffer ret = new StringBuffer(((len / 3) + 1) * 4);
        for (int i = 0; i < len; ++i) {
            c = (data[i] >> 2) & 0x3f;
            ret.append(cvt.charAt(c));
            c = (data[i] << 4) & 0x3f;
            if (++i < len)
                c |= (data[i] >> 4) & 0x0f;
            
            ret.append(cvt.charAt(c));
            if (i < len) {
                c = (data[i] << 2) & 0x3f;
                if (++i < len)
                    c |= (data[i] >> 6) & 0x03;
                
                ret.append(cvt.charAt(c));
            } else {
                ++i;
                ret.append((char) fillchar);
            }
            
            if (i < len) {
                c = data[i] & 0x3f;
                ret.append(cvt.charAt(c));
            } else {
                ret.append((char) fillchar);
            }
        }
        return ret.toString();
    }
    
    /**
     * Decodes a base64 String.
     *
     * @param data a base64 encoded String to decode.
     * @param the decoded String.
     */
    public static String decodeBase64(String data) {
        return decodeBase64(data.getBytes());
//      return data;
    }
    
    /**
     * Decodes a base64 aray of bytes.
     *
     * @param data a base64 encode byte array to decode.
     * @param the decoded String.
     */
    public static String decodeBase64(byte[] data) {
        int c, c1;
        int len = data.length;
        StringBuffer ret = new StringBuffer((len * 3) / 4);
        for (int i = 0; i < len; ++i) {
            c = cvt.indexOf(data[i]);
            ++i;
            c1 = cvt.indexOf(data[i]);
            c = ((c << 2) | ((c1 >> 4) & 0x3));
            ret.append((char) c);
            if (++i < len) {
                c = data[i];
                if (fillchar == c)
                    break;
                
                c = cvt.indexOf((char) c);
                c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
                ret.append((char) c1);
            }
            
            if (++i < len) {
                c1 = data[i];
                if (fillchar == c1)
                    break;
                
                c1 = cvt.indexOf((char) c1);
                c = ((c << 6) & 0xc0) | c1;
                ret.append((char) c);
            }
        }
        return ret.toString();
    }
    
    /**
     * javascript 跳转
     */
    public static String jsRedirect(String popMsg, String location) {
        StringBuffer result = new StringBuffer("");
        result.append("<script language='javascript'>");
        if (popMsg != null && !popMsg.trim().equals("")) {
            result.append("alert('" + popMsg + "');");
        }
        result.append(location);
        result.append("</script>");
        return result.toString();
    }
    /**
     * 处理oracle得到的时间字符串(得到格式为yyyy-MM-dd HH:mm:ss)
     * @param s
     * @return
     */
    public static String getOraTimeString(String s) {
        if (s == null || s.equals("")) {
            return "";
        }
        return s.substring(0, 19);
    }
    
    /**
     * 处理oracle得到的日期字符串(得到格式为yyyy-MM-dd)
     * @param s
     * @return
     */
    
    public static String getOraDateString(String s) {
        if (s == null || s.equals("")) {
            return "";
        }
        return s.substring(0, 10);
    }
    public static void main(String[] args){
        System.out.println(substring(10,"一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十"));
    }
    private static final int fillchar = '=';
    private static final String cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            + "abcdefghijklmnopqrstuvwxyz"
            + "0123456789+/";
}
